package servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import model.Goods;
import model.Order;
import service.GoodsService;

import java.io.IOException;
//购物车
@WebServlet(name = "goods_buy", urlPatterns = "/goods_buy")
public class GoodsBuyServlet extends HttpServlet {
    private GoodsService gService = new GoodsService();
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        拿取数据id
        int goodsid = Integer.parseInt(request.getParameter("goodsid"));
//        查询商品
        Goods goods = gService.getGoodsById(goodsid);
        
        if(goods.getStock() <= 0) {
            response.getWriter().print("fail");
            return;
        }
        
        Order order = (Order) request.getSession().getAttribute("order");
        if(order == null) {
            order = new Order();
            request.getSession().setAttribute("order", order);
        }
        order.addGoods(goods);
        response.getWriter().print("ok");
    }
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
} 